<template>
	<div class="box">
		<!-- <el-col :span="4" :xs="24">
			<el-card>
				<div class="head-container">
					<el-input v-model="deptName" placeholder="请输入查询的设备" clearable size="small"
						prefix-icon="el-icon-search" style="margin-bottom: 20px" />
				</div> -->
				<!--树形控件_部门数据-->
				<!-- <el-scrollbar style="height:70vh;">
					<el-tree :data="deptOptions" :props="defaultProps" :expand-on-click-node="true" accordion
						:filter-node-method="filterNode" ref="tree" node-key="id" :default-expanded-keys="[queryParams.deptId]" :highlight-current='true'
						@node-click="handleNodeClick"/>
				</el-scrollbar>
			</el-card>
		</el-col> -->
		<!--right-->
		<div>
			<el-dialog
			  title="修改素材"
			  :visible.sync="dialogVisible"
			  width="30%"
			  :before-close="handleClose">
			  <!-- 修改文件区 -->
			  <div class="imgBox" style="text-align: left; padding:5px 10px;">
			  	<el-upload class="upload-demos" drag action="" :multiple="false" :accept="suffix"
			  		:before-upload="beforePicUploadEdit">
			  		<i class="el-icon-upload"></i>
			  		<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
			  		<div class="el-upload__tip" slot="tip">只能上传jpg/jpeg/bmp/gif文件，且不超过1MB</div>
			  	</el-upload>
			  </div>  
			</el-dialog>
		</div>
		<el-col :span="24" :xs="24" style="padding: 10px;height: 100%;">
			<!-- 上传图片区 -->
			<p style="color:#000000;font-size: 18px;font-weight: 700;">上传文件</p>
			<div class="imgBox" style="text-align: left; padding:5px 10px;">
				<el-upload class="upload-demos" drag action="" :multiple="false" :accept="suffix"
					:before-upload="beforePicUpload">
					<i class="el-icon-upload"></i>
					<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
					<div class="el-upload__tip" slot="tip">只能上传jpg/jpeg/bmp/gif文件，且不超过1MB</div>
				</el-upload>
			</div>
			<p style="font-size: 18px;font-weight: 700;color: #000000;margin-top: 5px;">文件列表</p>
			<div class="buttomList" >
				<div style="color:gray;">
					<div class="fileChange">
						<span v-for="(item,index) in fileName" :class="{active:isNum==index}" :key="item"
							@click="fileListChange(index)">{{item}}</span>
						<el-button style="margin-left: 80px;padding: 0 5px;height:32px;margin-top: 4px;" type="success"
							plain :disabled="isDisabled" icon="el-icon-edit" size="mini" @click="handleEdit"
							v-hasPermi="['lgsv:material:edit']">修改</el-button>
						<el-button style="margin-left: 10px;padding: 0 5px;height:32px;margin-top: 4px;" type="danger"
							plain :disabled="isDisabled" icon="el-icon-delete" size="mini" @click="handleDelete"
							v-hasPermi="['lgsv:material:remove']">删除</el-button>	
					</div>
				</div>
				
				<div class="fileList" >
					<div style="position: absolute;top: -30px;left: 250px;">
						<el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">
							全选
						</el-checkbox>
					</div>
					<!-- v-loading="loading" -->
					<div v-show="total > 0">
						<el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
							<el-checkbox v-for="item in imgArr" :label="item.fFileId" :key="item.fFileId">
								<img :src="item.fRelativePath" alt="" :title="item.fDescription">
								<!-- <p>{{item.fDescription}}</p> -->
							</el-checkbox>
						</el-checkbox-group>
						<!-- 分页器 -->
						 <!-- v-show="total > 0" -->
						<pagination
							style='position: absolute;bottom: -70px;right: 5px;'
						  :total="total"
						  :page.sync="queryParams.pageNum"
						  :limit.sync="queryParams.pageSize"
						  @pagination="getMaterialList"
						/>
					</div>
					<div v-show="total <= 0" style="color: gray;font-weight: 700;text-align: center;height:50px;line-height: 50px;">暂无数据</div>
				</div>
			</div>
		</el-col>
	</div>
</template>

<script>
	import { mapState, mapMutations } from 'vuex'
	import {programsImg,delMaterial,getMaterial,editMaterial,getCard} from "@/api/system/program"
	import { treeselect } from "@/api/system/dept"; // 导入Tree树形Api
	import "@riophae/vue-treeselect/dist/vue-treeselect.css"; // 导入Tree树形css样式
	export default {
		name: "Material",
		data() {
			return {
				// 遮罩层
				iscreatWatch:false,
				loading: true,
				fileWidth:0,
				fileHeight:0,
				fileWidth2:0,
				fileHeight2:0,
				// 部门名称
				deptName: undefined,
				// 部门树选项
				deptOptions: undefined,
				// 修改素材
				dialogVisible: false,
				defaultProps: {
				  children: 'children',
				  label: 'label'
				},
				fFileId:undefined,
				deptId:undefined,
				fDescription:undefined,
				fIsMaterial:undefined,
				// 查询参数
				queryParams: {
				  pageNum: 1,
				  pageSize: 20,
				  // userName: undefined,
				  // phonenumber: undefined,
				  // status: undefined,
				  deptId: undefined
				},
				// 总条数
				total: 0,
				materialArr:[],
				checkAll: false,
				checkedCities: [],
				isIndeterminate: false,
				isDisabled: true,
				suffix: ".jpg,.bmp,.jpeg,.gif",
				imgFen: {
					"fFileId": 54, //图片ID
					"fFileUuid": 0,
					"mMessage": "", //文本ok
					"mPath": "", //图片路劲		
				},
				imgArr: [],
				isNum: 0,
				fileName: ["全部", "图片", "GIF"],
				// 文件参数
				paramsData: {
					fileType: 0
				},
				// 文件描述
				dialogImageUrl: [0, 1, 2]
			}
		},
		watch:{
			// 根据名称筛选部门树
			deptName(val) {
			  this.$refs.tree.filter(val);
			},
			"$store.state.deptId": {
			      handler(newval) {
						this.queryParams.deptId=newval
						this.getMaterialList() //查询素材列表
						getCard(newval).then(res=>{
							this.fileWidth=res.data.width
							this.fileHeight=res.data.height
						})  
			      }
			}
		},
		mounted() {
			if(this.$store.state.deptId){
				this.queryParams.deptId=this.$store.state.deptId
				this.getMaterialList() //查询素材列表
				getCard(this.queryParams.deptId).then(res=>{
					this.fileWidth=res.data.width
					this.fileHeight=res.data.height
				})
			}
		},
		methods: {
			/** 查询部门下拉树结构*/
			// getTreeselect () {
			//   treeselect().then(response => {
			//     this.deptOptions = response.data
			// 	this.queryParams.deptId=this.deptOptions[0].id
			// 	getCard(this.deptOptions[0].id).then(res=>{
			// 					  this.fileWidth=res.data.width
			// 					  this.fileHeight=res.data.height
			// 	})
			//   })
			// },
			// 发送节目设备下拉树
			// filterNode(value, data) {
			//     if (!value) return true;
			//     return data.label.indexOf(value) !== -1;    
			// },
			// 节点单击事件
			// handleNodeClick (data) {
			//   this.flag = false
			//   this.queryParams.deptId=data.id
			//   this.getMaterialList() //查询素材列表
			//   getCard(data.id).then(res=>{
			// 	  this.fileWidth=res.data.width
			// 	  this.fileHeight=res.data.height
			//   })
			// },
			// 查询素材列表
			getMaterialList(){
				this.loading = true;
				this.imgArr=[];
				getMaterial(this.queryParams).then(
				  response => {
					this.materialArr=response.rows
					if(this.isNum==0){
						this.materialArr.forEach(item=>{
							if(item.fType==3||item.fType==2){
								this.imgArr.push(item)
							}
						})
						// this.imgArr=this.materialArr
						this.total = this.imgArr.length;
					}else if(this.isNum==1){
						this.materialArr.forEach(item=>{
							if(item.fType==2){
								this.imgArr.push(item)
							}
						})
						this.total = this.imgArr.length;
					}else if(this.isNum==2){
						this.materialArr.forEach(item=>{
							if(item.fType==3){
								this.imgArr.push(item)
							}
						})
						this.total = this.imgArr.length;
					}
				    this.loading = false;
				  }
				);	
			},
			handleCheckAllChange(val) {
				let arr = []
				this.imgArr.forEach(item => {
					arr.push(item.fFileId)
				})
				this.checkedCities = val ? arr : [];
				if (this.checkedCities.length > 0) {
					this.isDisabled = false
				} else {
					this.isDisabled = true
				}
				this.isIndeterminate = false;
			},
			handleCheckedCitiesChange(value) {
				let checkedCount = value.length;
				this.imgArr.forEach(item=>{
					if(item.fFileId==value[0]){
						this.fFileId=item.fFileId
						this.deptId=item.deptId
						this.fDescription=item.fDescription
						this.fIsMaterial=item.fIsMaterial	
					}
				})
				this.checkAll = checkedCount === this.imgArr.length;
				if (this.checkedCities.length > 0) {
					this.isDisabled = false
				} else {
					this.isDisabled = true
				}
				this.isIndeterminate = checkedCount > 0 && checkedCount < this.imgArr.length;
			},
			// 修改素材弹出菜单
			handleClose(done) {
			        this.$confirm('确认关闭？')
			          .then(_ => {
			            done();
			          })
			          .catch(_ => {});
			},
			// 文件列表切换
			fileListChange(index) {
				this.isNum = index
				this.checkAll=false
				this.isDisabled = true
				this.isIndeterminate = false;
				this.checkedCities=[]
				this.getMaterialList() //查询素材列表
			},
			// 添加图片
			beforePicUpload(file) {
				const isLt1M = file.size / 1024 / 1024 < 1
				if (!isLt1M) {
					this.$message.error('上传文件大小不能超过 1MB!')
					return false
				}
				// 宽高限制
				let width=this.fileWidth;
				let height=this.fileHeight;
				let widths=0;
				let heights=0;
				const isSize = new Promise(function(resolve, reject){
				    let _URL = window.URL || window.webkitURL;
				    let img = new Image();
				    img.onload = function(){
						let valid = img.width <= width && img.height <= height;
						widths=img.width
						heights=img.height
						valid ? resolve() : reject();
				    }
				     img.src = _URL.createObjectURL(file);
				}).then(()=>{
				    //图片接口
				    programsImg([file],this.queryParams.deptId,1,widths,heights).then(res => {
				    	if (res.code == 200) {
							this.getMaterialList() //查询素材列表
				    		this.$message.success(res.msg)
				    	} else {
				    		this.$message.error(res.msg)
				    	}
				    })
				}, ()=>{
					this.$message.error('只能添加尺寸小于'+width+'*'+height+'的文件!请重新选择!')
				    return false;//必须加上return false; 才能阻止
				})
				return false
			},
			// 修改图片
			beforePicUploadEdit(file){
				const isLt1M = file.size / 1024 / 1024 < 1
				if (!isLt1M) {
					this.$message.error('上传文件大小不能超过 1MB!')
					return false
				}
				// 宽高限制
				getCard(this.deptId).then(res=>{
					let width=res.data.width
					let height=res.data.height
					let widths=0;
					let heights=0;
					const isSize = new Promise(function(resolve, reject){
					    let _URL = window.URL || window.webkitURL;
					    let img = new Image();
					    img.onload = function(){
							let valid = img.width <= width && img.height <= height;
							widths=img.width
							heights=img.height
							valid ? resolve() : reject();
					    }
					     img.src = _URL.createObjectURL(file);
					}).then(()=>{
					    // 图片接口
					    editMaterial([file],this.fFileId,this.deptId,this.fIsMaterial,widths,heights).then(res => {
					    	if (res.code == 200) {
								this.getMaterialList() //查询素材列表
					    		this.$message.success(res.msg)
								this.dialogVisible = false
					    	} else {
					    		this.$message.error(res.msg)
					    	}
					    })
					}, ()=>{
						this.$message.error('修改的文件尺寸只能小于'+width+'*'+height+' ,请重新选择!')
					    return false;//必须加上return false; 才能阻止
					})
				})
				return false
			},
			/** 删除按钮操作 */
			handleDelete() {
				let that = this
				this.$confirm('确定要删除选中的数据吗?', "警告", {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(function() {
					return delMaterial(that.checkedCities)
				}).then(() => {
					this.imgArr = []
					this.checkedCities = []
					this.checkAll = false
					this.getMaterialList() //查询素材列表
					this.msgSuccess('删除成功')
				})
			},
			// 修改素材进入按钮
			handleEdit(){
				if(this.checkedCities.length!=1){
					 this.$message({
						 showClose: true,
					           message: '一次只能修改一个素材',
					           type: 'warning'
					         });
				}else{
					this.dialogVisible = true
				}
			},
		}
	}
</script>

<style lang='scss' scoped="scoped">
	* {
		margin: 0;
		padding: 0;
	}

	.box {
		/* padding: 10px; */
		/* background-color: #ffebcd; */
		/* border: 1px solid red; */
		height: 100%;
		width: 100%;
		.buttomList {
			border: 1px solid gray;
			margin-top: 3px;
			height:420px;
		}

		.fileChange {
			display: flex;
			background-color: #ffebcd;
			span {
				text-align: center;
				line-height: 40px;
				width: 80px;
				font-weight: 700;
				height: 40px;
				cursor: pointer;
				
				&:hover {
					background-color: rgba(205, 211, 202, .7);
					color: #dd5246;
				}

				&.active {
					background-color: #cdd3ca;
					color: #dd5246;
				}
			}
		}

		.imgBox {
			border: 1px solid gray;
			background-color: rgba(41, 183, 204, .3);

			.inputBox {
				display: flex;
				align-items: center;
				width: 400px;
				margin-bottom: 5px;
				color: dimgray;

				.el-input {
					width: 200px;
				}
			}
		}
		.fileList {
			background-color: #fff;
			position: relative;
			width: 100%;
			height:80%;
			.el-checkbox-group {
				width: 100%;
				max-height: 370px;
				overflow-y: auto;
				display: flex;
				flex-wrap: wrap;
				padding: 5px;
				align-content: flex-start;
				.el-checkbox {
					border: 1px solid gray;
					border-radius: 5px;
					margin-right: 5px;
					padding: 5px;
					margin-bottom: 5px;
					text-align: center;
					position: relative;
					::v-deep.el-checkbox__input {
						position: absolute;
						left: 5px;
						top: 5px;
					}
					p {
						position: absolute;
						bottom: -20px;
						left: 50%;
						transform: translateX(-50%);
					}
					img {
						height: 100%;
					}
				}
			}
		}
	}

	::v-deep.upload-demos {
		height: 120px;
		display: flex;
		position: relative;

		.el-upload-dragger {
			width: 150px;
			height: 100px;
			text-align: center;

			.el-icon-upload {
				margin: 0;
			}
		}

		.el-upload__tip {
			position: absolute;
			top: 100px
		}
	}
</style>
